using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
//
// DotNetNuke - http://www.dotnetnuke.com
// Copyright (c) 2002-2010
// by DotNetNuke Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//


using DotNetNuke.UI.Utilities;
using DotNetNuke.Security.Permissions;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Definitions;
using DotNetNuke.Application;
using DotNetNuke.Entities.Host;
using DotNetNuke.Services.FileSystem;
using DotNetNuke.Web.UI;

using Telerik.Web.UI;
using DotNetNuke.Common;
using DotNetNuke.Entities.Tabs;
using DotNetNuke.Services.Localization;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Security;

namespace DotNetNuke.UI.ControlPanel
{

	partial class AddPage : System.Web.UI.UserControl, DotNetNuke.Web.UI.WebControls.IDnnRibbonBarTool
	{

		#region "Event Handlers"


		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);
		}

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

			cmdAddPage.Click += new EventHandler(cmdAddPage_Click);

			try
			{
				if (!IsPostBack)
				{
					if ((Visible))
					{
						LoadAllLists();
					}
				}
				//Module failed to load
			}
			catch (Exception exc)
			{
				DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}

		protected override void OnPreRender(EventArgs e)
		{
			base.OnPreRender(e);
		}

		protected void cmdAddPage_Click(object sender, System.EventArgs e)
		{
			TabController tabCtrl = new TabController();

			int selectedTabID = Int32.Parse(PageLst.SelectedValue);
			DotNetNuke.Entities.Tabs.TabInfo selectedTab = tabCtrl.GetTab(selectedTabID, PortalSettings.ActiveTab.PortalID, false);
			TabRelativeLocation tabLocation = (TabRelativeLocation)Enum.Parse(typeof(TabRelativeLocation), LocationLst.SelectedValue);
			DotNetNuke.Entities.Tabs.TabInfo newTab = RibbonBarManager.InitTabInfoObject(selectedTab, tabLocation);

			string templateFile = "";
			if ((!string.IsNullOrEmpty(TemplateLst.SelectedValue)))
			{
				templateFile = System.IO.Path.Combine(PortalSettings.HomeDirectoryMapPath, "Templates\\" + TemplateLst.SelectedValue);
			}

			newTab.TabName = Name.Text;
			newTab.IsVisible = IncludeInMenu.Checked;

			string errMsg = "";
			try
			{
				RibbonBarManager.SaveTabInfoObject(newTab, selectedTab, tabLocation, templateFile);
			}
			catch (DotNetNukeException ex)
			{
				DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
				if ((ex.ErrorCode != DotNetNukeErrorCode.NotSet))
				{
					errMsg = GetString("Err." + ex.ErrorCode.ToString());
				}
				else
				{
					errMsg = ex.Message;
				}
			}
			catch (Exception ex)
			{
				DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
				errMsg = ex.Message;
			}

			//Clear the Tab's Cached modules
			DotNetNuke.Common.Utilities.DataCache.ClearModuleCache(PortalSettings.ActiveTab.TabID);

			//Update Cached Tabs as TabPath may be needed before cache is cleared
			DotNetNuke.Entities.Tabs.TabInfo tempTab = null;
			if (new TabController().GetTabsByPortal(PortalSettings.ActiveTab.PortalID).TryGetValue(newTab.TabID, out tempTab))
			{
				tempTab.TabPath = newTab.TabPath;
			}

			if ((string.IsNullOrEmpty(errMsg)))
			{
				Response.Redirect(DotNetNuke.Common.Globals.NavigateURL(newTab.TabID));
			}
			else
			{
				//Show error
				errMsg = GetString("Err.Header") + "<br /><br />" + errMsg;
				DotNetNuke.Web.UI.Utilities.RegisterAlertOnPageLoad(this, errMsg);
			}
		}

		#endregion

		#region "Properties"

		public string ToolName
		{
			get { return "QuickAddPage"; }
			set
			{
				throw new NotSupportedException("Set ToolName not supported");
			}
		}

		public override bool Visible
		{
			get { return base.Visible && TabPermissionController.CanAddPage(); }
			set { base.Visible = value; }
		}

		#endregion

		#region "Methods"

		private DotNetNuke.Entities.Tabs.TabInfo _NewTabObject = null;
		protected DotNetNuke.Entities.Tabs.TabInfo NewTabObject
		{
			get
			{
				if (((_NewTabObject == null)))
				{
					_NewTabObject = RibbonBarManager.InitTabInfoObject(PortalSettings.ActiveTab);
				}
				return _NewTabObject;
			}
		}

		private void LoadAllLists()
		{
			LoadLocationList();
			LoadTemplateList();
			LoadPageList();
		}

		private void LoadTemplateList()
		{
			TemplateLst.ClearSelection();
			TemplateLst.Items.Clear();

			//Get Templates Folder
			ArrayList templateFiles = Common.Globals.GetFileList(PortalSettings.PortalId, "page.template", false, "Templates/");
			foreach (FileItem dnnFile in templateFiles)
			{
				RadComboBoxItem item = new RadComboBoxItem(dnnFile.Text.Replace(".page.template", ""), dnnFile.Text);
				TemplateLst.Items.Add(item);
				if ((item.Text == "Default"))
				{
					item.Selected = true;
				}
			}

			TemplateLst.Items.Insert(0, new RadComboBoxItem(GetString("NoTemplate"), ""));
		}

		private void LoadLocationList()
		{
			LocationLst.ClearSelection();
			LocationLst.Items.Clear();

			LocationLst.Items.Add(new RadComboBoxItem(GetString("Before"), "BEFORE"));
			LocationLst.Items.Add(new RadComboBoxItem(GetString("After"), "AFTER"));
			LocationLst.Items.Add(new RadComboBoxItem(GetString("Child"), "CHILD"));

			if ((!PortalSecurity.IsInRole("Administrators")))
			{
				LocationLst.SelectedIndex = 2;
			}
			else
			{
				LocationLst.SelectedIndex = 1;
			}
		}

		private void LoadPageList()
		{
			PageLst.ClearSelection();
			PageLst.Items.Clear();

			PageLst.DataTextField = "IndentedTabName";
			PageLst.DataValueField = "TabID";
			PageLst.DataSource = RibbonBarManager.GetPagesList();
			PageLst.DataBind();

			RadComboBoxItem item = PageLst.FindItemByValue(PortalSettings.ActiveTab.TabID.ToString());
			if (((item != null)))
			{
				item.Selected = true;
			}
		}

		private string LocalResourceFile
		{
			get { return string.Format("{0}/{1}/{2}.ascx.resx", this.TemplateSourceDirectory, Localization.LocalResourceDirectory, this.GetType().BaseType.Name); }
		}

		private string GetString(string key)
		{
			return Localization.GetString(key, LocalResourceFile);
		}

		private PortalSettings PortalSettings
		{
			get { return DotNetNuke.Entities.Portals.PortalSettings.Current; }
		}

		#endregion

	}

}


